#include "RunState.h"
#include "utils\Timer.h"
#include "utils\Log.h"
#include "base\Engine.h"
#include "Constants.h"
#include "renderer\DebugRenderer.h"
#include "SimpleStates.h"

RunState::RunState(std::string name,GameCore* core) : GameState(name) , m_Core(core) {
	gEngine->getEventManager().registerEventHandler(this);
}

void RunState::switchState(States state) {	
	if ( state == PLAYING ) {
		gEngine->getActionManager().startAction("CheckCoverage");
		gEngine->getActionManager().startAction("RunLaser");
		gEngine->getActionManager().startAction("HandleMouse");
		gEngine->getActionManager().startAction("ShowGrid");
	}
	else if ( state == GAME_OVER ) {
		gEngine->getActionManager().stopAction("CheckCoverage");
		gEngine->getActionManager().stopAction("RunLaser");
		gEngine->getActionManager().stopAction("HandleMouse");
		gEngine->getActionManager().stopAction("ShowGrid");
		
		m_Core->score().gameOver = true;
		if ( m_Core->settings().coverageMode && m_Core->score().coverage > m_Core->settings().coverage ) {
			m_Core->score().gameOver = false;
		}
		if ( m_Core->settings().timerMode &&m_Core->score().coverage > 50 ) {
			m_Core->score().gameOver = false;
		}
		gEngine->getActionManager().startAction("GameOverMenu");
	}	
}

void RunState::process(ds::EventBuffer& buffer ) {		
	if ( buffer.containsID(EVN_START_GAME)) {
		LOG(logINFO) << "EVN_START_GAME";
		buffer.getByID(&m_Core->settings(),sizeof(GameSettings),EVN_START_GAME);
		switchState(PLAYING);
		if ( m_Core->settings().timerMode ) {
			m_Core->hud().setTTL(m_Core->settings().ttl);
		}
		else {
			m_Core->hud().setTTL(0);
		}
	}
	if ( buffer.containsID(EVN_TIME_ELAPSED)) {
		switchState(GAME_OVER);
	}
	if ( buffer.containsID(EVN_COVERAGE_DONE)) {
		switchState(GAME_OVER);		
	}	
}


